<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<?php include("config.php");?>
<html>
<head>
	<title>Mapguide Tile Seeder</title>
	<script src="OpenLayers/lib/OpenLayers.js"></script>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
	<script>

	$(document).ready(function(){

		b_pause=document.getElementById('b_pause');
		b_stop=document.getElementById('b_stop');
		region = 'Bykom TileCacheSeeder: ' + prompt('Introduce region a tilear:','');

		x1 = prompt('Introduce X1:','');
		y1 = prompt('Introduce Y1:','');
		x2 = prompt('Introduce X2:','');
		y2 = prompt('Introduce Y2:','');
		region += " (" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ")";
		document.getElementById('titleString').innerHTML = region;
		if (x1 == null || x2 == null || y1 == null || y2 == null) {
			alert('Se han cargado valores no validos en los bounds de usuario');
			return;
		}
		initTiled();
	})


</script>
</head>

<body onbeforeunload="alert('cerrando ventanas y deslogueando');">
<h1><span id="titleString"></span></h1>
<script>
		var windowSize=650;
        var map, layer;
        var x1,y1,x2,y2;
        extent = new OpenLayers.Bounds( <?=BOUNDSX1?>, <?=BOUNDSY1?>, <?=BOUNDSX2?>, <?=BOUNDSY2?>);
        //userBounds = new OpenLayers.Bounds(-59,-34.5,-58,-35);

		<? if (AVL_USE_HTTP_TILE == 1) { ?>
    		url = "http://<?=AVL_MAP_SERVER_IP?>:<?=AVL_MAP_SERVER_PORT?>/bykomTiles";
		<? } else { ?>
			url = "http://<?=AVL_MAP_SERVER_IP?>:<?=AVL_MAP_SERVER_PORT?>/mapguide/mapagent/mapagent.fcgi?USERNAME=<?=AVL_MAP_SERVER_ADMIN?>&PASSWORD=<?=AVL_MAP_SERVER_PASSW?>&";
		<? }?>

		var eventsLog = "";
		var c=0;
        //tiled version

        function initTiled(){
        	userBounds = new OpenLayers.Bounds(x1,y1,x2,y2);
			eventsLog = OpenLayers.Util.getElement("eventsLogID");
			var divWin=document.getElementById('map');
			divWin.style.width=windowSize;
			divWin.style.height=windowSize;


            OpenLayers.DOTS_PER_INCH = 96;


        	var tempScales = <?=AVL_SCALES_LIST?>;
			projection = new OpenLayers.Projection("EPSG:4326");
       		displayProjection = new OpenLayers.Projection("EPSG:4326");

            mapOptions = {
				projection: projection,
				displayProjection: displayProjection,
        		maxExtent: extent,
        		restrictedExtent: userBounds,
            	scales: tempScales
        	};

            map = new OpenLayers.Map( 'map', mapOptions );

			var params = {
              	mapdefinition: '<?=AVL_MAP_DEFINITION?>',
        		basemaplayergroupname: "<?=AVL_MAP_BASE_LAYER_GROUP?>"
            }
			var options = {
        		singleTile: false,
        		<? if (AVL_USE_HTTP_TILE == 1) {
       	 			echo ' useHttpTile:true, buffer: 0, EVENT_TYPES:["loadstart", "loadend", "loadcancel","visibilitychanged","tileloaded"]';
        		} ?>
    		}

            layer = new OpenLayers.Layer.MapGuide( "MapGuide OS tiled layer", url, params, options );
			registerEvents(layer);
            map.addLayer(layer);
			map.zoomToMaxExtent();
			map.setCenter(extent.getCenterLonLat());

			map.addControl(new OpenLayers.Control.MousePosition());
 			var s_zoom=document.getElementById('s_zoom');
  			for (z=0; z < map.getNumZoomLevels() ; z++){
				s_zoom.options[z] = new Option(z + ': ' + map.getResolutionForZoom(z)*1000000, z);
			}

			map.events.register("zoomend", map, setZoom);



		}

		function setZoom(){
			var s_zoom=document.getElementById('s_zoom');
			s_zoom.selectedIndex=map.getZoom();
		}

		function doZoom(){
			var s_zoom=document.getElementById('s_zoom');
			map.zoomTo(s_zoom.value);
		}

		var moveDirection='initial_left';
		var seeding=false;
		var didMove=true;
		var wait=false;
		var wait_count=0
		var all_scales="";
		var ar_scales="";
		var col=0;
		var row=0;
		var row_total=0;
		var col_total=0;

		var tile_array="";
		var tile_built=false;
		var total_tiles=0;

		function showColRow(){

			return tile_built;
		}

		function buildTileArray(){
			var ff_col=document.getElementById('col');
			var ff_row=document.getElementById('row');
			ff_col.value=col;
			ff_row.value=row;
			var cb_random=document.getElementById('cb_random');

			if (!tile_built){
				var ff_remaining=document.getElementById('pan_remaining');
				total_tiles=(col_total*row_total);
				ff_remaining.value=total_tiles;
			}


			if (!tile_built && cb_random.checked) {


				tile_array= new Array(col_total);
				for ( var ct =0 ; ct < col_total ; ct ++){
					tile_array[ct]= new Array(row_total);
					for ( var rt =0 ; rt < row_total ; rt ++){
						tile_array[ct][rt]=false;
					}
				}
				tile_built=true;
				next_col=col_total;
					next_row=1;
				changeDirection('random');
			} else {
				tile_built=true;
				changeDirection('moveDownOneLeft');
			}


			log ("total tiles: " + total_tiles +'<br>');
			reSeedAtEdge();
		}

		function setMaxCol(col){
			var ff_col_count=document.getElementById('col_count');
			ff_col_count.innerHTML='('+col+')';
			col_total=col;
		};

		function setMaxRow(row){
			var ff_row_count=document.getElementById('row_count');
			ff_row_count.innerHTML='('+row+')';
			row_total=row;
		};

		function goCenter(){
			map.setCenter(extent.getCenterLonLat());
		};


		function changeDirection(dir){
			moveDirection=dir;
			eventsLog.innerHTML="";
			log('<strong>Change Direction:</strong>'+dir+'<br>');
			var ff_dir=document.getElementById('dir');
			ff_dir.value=dir;
		}

		function log(mess){
			eventsLog.innerHTML +=mess;

			eventsLog.scrollTop = eventsLog.scrollHeight;

			return;
		}

		var next_col;
		var next_row;

		var last_row;
		var last_col;


		function seedCache(){

			if (!seeding)
				return;


			var infoStr=document.getElementById('info');

			log('<strong>Direction:</strong> '+moveDirection+'<br>');

			if (moveDirection=='initial_left'){
				didMove=pan(-windowSize,0);
				if (!didMove){
					changeDirection('initial_down');
				}
				reSeedAtEdge();
				return;

			}

			if (moveDirection=='initial_down'){
				didMove=pan(0,windowSize);
				if (!didMove){
					col=0;
					changeDirection('initial_up');
				}
				reSeedAtEdge();
				return;
			}

			if (moveDirection=='initial_up'){
				didMove=pan(0,-windowSize);
				col=col+1;
				if (!didMove){
					setMaxCol(col);
					col=0;
					changeDirection('moveRight');
				}
				reSeedAtEdge();
				return;
			}


			if (moveDirection=='moveRight'){
				row=row+1;
				didMove=pan(windowSize,0);
				if (!didMove){
					setMaxRow(row);
					buildTileArray();
				} else {
					reSeedAtEdge();
				}
				return;
			}

			if (moveDirection=='moveLeft'){
				row=row-1;
				didMove=pan(-windowSize,0);
				if (!didMove){
					changeDirection('moveDownOneRight');
				}
				reSeedAtEdge();
				return;
			}

			if (moveDirection=='moveDownOneRight'){
				col=col+1;
				didMove=pan(0,windowSize);
				if ( didMove) {
					changeDirection('moveRight');
				}	else {
					FinishedSeedCache();
					return;
				}
				reSeedAtEdge();
				return;
			}

	 		if (moveDirection=='moveDownOneLeft'){
				col=col+1;
				didMove=pan(0,windowSize);
				if ( didMove) {
					changeDirection('moveLeft');
				}	else {
					FinishedSeedCache();
					return;
				}
				reSeedAtEdge();
				return;
			}

			if (moveDirection=='random'){
				var found_next=false;
				last_col=next_col;
				last_row=next_row;
				var random_attempts=0;

				while (!found_next){
					random_attempts++;
					if (random_attempts==total_tiles){
						changeDirection('finished');
						break;
					} else {
						next_col=Math.floor(Math.random()*col_total);
						next_row=Math.floor(Math.random()*row_total);
						//log('chk:' + next_col + ' , ' + next_row +'<br>');
						if (!tile_array[next_col][next_row])
							found_next=true;
					}
				}

				if(!seeding)
					return; // ie finished

				if (found_next){
					log('Random:' + next_col + ' , ' + next_row +' (' + last_col + ' , ' + last_row
						+ ') move xy: ' +(last_col-next_col)*windowSize + ', ' + (last_row-next_row)*windowSize );
					pan((last_col-next_col)*windowSize , (last_row-next_row)*windowSize);

					var ff_col=document.getElementById('col');
					var ff_row=document.getElementById('row');
					ff_col.value=next_col;
					ff_row.value=next_row;

					tile_array[next_col][next_row]=true;
					reSeedAtEdge();
				}
			}

			if (moveDirection=='finished')
				FinishedSeedCache();
		}

		function reSeedAtEdge(){
			if ( layer.numLoadingTiles < 3) {
				//log('<strong>RE_SEEDING</strong>');
				seedCache();
			}
		}


		 function registerEvents(layer) {

            layer.logEvent = function(event) {
                log("<br>(" + getTimeStamp() + ") " +   this.name + ": " + event + '<br>');
            }

            layer.events.register("loadstart", layer, function() {
                log("<br>(" + getTimeStamp() + ") Load Start  ");
            });

            layer.events.register("tileloaded", layer, function() {
                log( this.numLoadingTiles + " ...");
/*				if ( layer.numLoadingTiles < 3
					&& moveDirection !='moveDownOneRight'
					&& moveDirection !='moveDownOneLeft')  {
					//log('<strong>RE_SEEDING</strong>');
					seedCache();
				}	*/
            });

            layer.events.register("loadend", layer, function() {
//				eventsLog.innerHTML ="";
	//			log("<br>(" + getTimeStamp() + ") Load End. Grid:" + this.grid.length + "x" + this.grid[0].length);
				if ( seeding )
					setTimeout('seedCache()',250);
            });

            map.addLayer(layer);
        }

		function getTimeStamp() {
            var date = new Date();

            var timeParts = [
                date.getHours(),
                date.getMinutes(),
                date.getSeconds()
            ];

            var timeStamp = timeParts.join(":");

            return timeStamp;
        }

        function clearLog() {
            eventsLog.innerHTML = "<b>Events Log:</b>";
        }



		function pan(x,y){
			c++;
			var count=document.getElementById('c');
			count.value=c;
			var startBounds=map.getExtent();


			/*if (!startBounds.contains(userBounds)) {
				alert('no!');
				return 0;
			}*/


			map.pan(x,y);
			var infoStr=document.getElementById('info');
			// use toBBOX to round, other wise it doesn't always match


			if (startBounds.toBBOX(8) == map.getExtent().toBBOX(8))
				var didMove=0;
			else
				var didMove=1;

			infoStr.value=didMove;
			//alert('<br>Pan(' + x + ',' + y + ')= bounds changed =' +didMove + "<br> "  +startBounds + '<br>'	+ map.getExtent().toBBOX(7));
			log('<br>Pan(' + x + ',' + y + ')= bounds changed =' +didMove + "<br> "  +startBounds + '<br>'	+ map.getExtent().toBBOX(7));



			if (tile_built) {
				var ff_remaining=document.getElementById('pan_remaining');
				ff_remaining.value=ff_remaining.value-1;
				document.title=ff_remaining.value;
			}


			return didMove;
		}




		function StartSeedCache(){
			var d = new Date();
			document.title="Starting!";
			seeding=true;
			tile_built=false;
			b_pause.disabled=false;
			b_pause.value="pause";
			b_stop.disabled=false;
			cb_all_scales=document.getElementById('cb_all_scales');
			if (cb_all_scales.checked){
				all_scales=true;
				map.zoomTo(0);
				ar_scales= new Array(1);
	  			for (var z=0; z < map.getNumZoomLevels() ; z++)
					ar_scales[z]=false
				ar_scales[0]=true
			}else{
				all_scales=false;
			}
			changeDirection('initial_left');
			c=0;
			document.getElementById('start_time').innerHTML=d;
			document.getElementById('end_time').innerHTML="";
			seedCache();
			setMaxCol(-1);
			setMaxRow(-1);

		}
		function StopSeedCache(){

			seeding=false;
			b_pause.value="pause";
			b_pause.disabled=true;
			b_stop.disabled=true;
			log('<strong>SEEDING STOPPED</strong>	');
		};

		function PauseSeedCache(){

			if (seeding){
				log('<strong><blink>----------- PAUSED ----------</blink></strong><br>	');
				seeding=false;
				b_pause.value="resume";
			} else {
				seeding=true;
				b_pause.value="Pause";
				reSeedAtEdge();
			}
		};

		function FinishedSeedCache(){
			if (!seeding)
				return;
			if(all_scales){
				for (var z=0; z < map.getNumZoomLevels() ; z++){
					if(ar_scales[z] ==false){
						ar_scales[z]=true;
						tile_built=false;
						map.zoomTo(z);
						goCenter();
						setMaxCol(-1);
						setMaxRow(-1);
						row=0;
						col=0;
						var ff_remaining=document.getElementById('pan_remaining');
						ff_remaining.value=0;
						changeDirection('initial_left');
						seedCache();
						return;
					}
				}
			}

			seeding=false;
			log('<strong>FINISHED SEEDING</strong><br>	');

			b_pause.value="pause";
			b_pause.disabled=true;
			b_stop.disabled=true;
			goCenter();
			var d = new Date();
			document.getElementById('end_time').innerHTML=d;
			document.title="Finished!";
		}




</script>

<div id="map" style="border: medium inset Maroon; float: left; background-color: #F5DEB3;"></div>
<div id="eventsLogID" style="height: 500px; width: 500px; border: medium inset Maroon;
	font-family: Arial, Helvetica, sans-serif; font-size: 8px;overflow: scroll;"></div>
<br>

<form autocomplete="off">


<input type="button" value="Centre" onclick="goCenter();">
&nbsp;
<input type="button" value="Extent" onclick="map.zoomToMaxExtent();">
&nbsp;

Scale: <select name="zoom" size="1" id="s_zoom" onChange="doZoom()">
</select>
<input type="button" value="Zoom" onclick="doZoom();">
<br>

<input type="button" value="start seeding" onclick="StartSeedCache();">
<input type="button" value="pause seeding" id="b_pause" onclick="PauseSeedCache();" disabled>
<input type="button" value="stop seeding" id="b_stop" onclick="StopSeedCache();" disabled>

Randomise : <input type="checkbox" name="random" id="cb_random" value="1">

Process All Scales : <input type="checkbox" name="all_scales" id="cb_all_scales" value="0" checked>

<br>
start time: <span id="start_time"></span><br>
end time: <span id="end_time"></span>
<br>


Current Direction <input type="text" id="dir" size="15"> <br>

Completed <input type="text" id="c" size="5">
Remaining <input type="text" id="pan_remaining" size="5">
&nbsp;&nbsp;

row <input type="text" id="row" size="6"> <span id="row_count"></span>

col <input type="text" id="col" size="6"> <span id="col_count"></span>


<input type="hidden" id="info" size="50">
</form>

<br clear="all">
</body>
</html>
